import Markdown from './markdown';
import {unicodeToChinese} from './';
import cheerio from 'cheerio';
import fs from 'fs-extra';

export default function parseSummary(md, prepath){
	const exists = fs.existsSync(md);
	if (!exists) return;
	const summaryCache = md.replace(/\.md$/i,'.cache');
	const hasCached = fs.existsSync(summaryCache);
	if (hasCached) {
		try{
			return fs.readFileSync(summaryCache,'utf8');
		}catch(e){
			console.log(e);
		}
	}
	const htm = Markdown.render(fs.readFileSync(md,'utf8'));
	const $ = cheerio.load(htm);
	let navs = [];
	$('ul').first().children().each(function(ins,ele){
		let subul = $(this).find('ul');
		let hasChild = subul.length;
		let value = subul.html();
		let brReg = /[\r\n\\n]/ig;
		subul.empty();
		navs.push({
			id: Math.random().toString(23).slice(2,18),
			name: escape(mapMDtoHTM(prepath, unicodeToChinese(!hasChild? $(this).html(): $(this).html().replace(/<.+?>/ig,'').replace(brReg,'')))),
			value: escape(mapMDtoHTM(prepath, unicodeToChinese(!hasChild? null: value.replace(brReg,'')))),
			hasChild
		});
	});
	navs = JSON.stringify(navs);
	fs.writeFileSync(summaryCache,navs);
	return navs;
} 
;

function mapMDtoHTM(prepath, src){
	return ((src? src.replace(/(src|href)=(['"])(.+?)\2/gi,function(a,b,c,d){
		return ' '+b+'="'+prepath + d.replace(/\.md(.*?)$/i,'.html$1')+'"';
	}): '')).replace(/(\/)+/gi,'$1');
}